<?php
/**
 * Created by PhpStorm.
 * User: aiChenK
 * Date: 2019-01-02
 * Time: 10:49
 */

namespace Services\Sys;

use Helpers\Main;
use Helpers\Tool;
use Services\Sys\Models\XhovertValidcode;

class ValidCode
{

    const TYPE_DEFAULT = 0;
    const TYPE_REGISTER = 1;
    const TYPE_LOGIN = 2;
    const TYPE_CHANGE_PWD = 3;
    const TYPE_CHANGE_PHONE = 4;
    const TYPE_SALARY = 5;

    /**
     * 发送短信验证码
     *
     * @param $phone
     * @param null $code
     * @param string $module
     * @param string $subModule
     * @param int $type
     * @throws \Exception
     *
     * create by ck 20190109
     */
    public static function send($phone, $code = null, $module = '', $subModule = '', $type = self::TYPE_DEFAULT)
    {
        if (!preg_match('/^1[3456789]{1}\d{9}$/', $phone)) {
            throw new \Exception('手机号格式不正确');
        }
        if (!$code) {
            $code = Tool::getRand(6);
        }
        $validCode              = new XhovertValidcode();
        $validCode->sSelfPhone  = $phone;
        $validCode->iVCode      = $code;
        $validCode->tCreateTime = date('Y-m-d H:i:s');
        $validCode->tExpireTime = date('Y-m-d H:i:s', strtotime($validCode->tCreateTime) + 60 * 10);
        $validCode->iCodeType   = $type;
        $validCode->iState      = 0;
        if (!$validCode->save()) {
            throw new \Exception('验证码生成失败');
        }
        Main::sendSMS($phone, "您的验证码：{$code}，十分钟内有效。", $module, $subModule);
    }

    /**
     * 检查验证码是否有效
     *
     * @param $phone
     * @param $validCode
     * @param int $type
     * @return bool
     *
     * create by ck 20190109
     */
    public static function check($phone, $validCode, $type = self::TYPE_DEFAULT)
    {
        $checkCode = XhovertValidcode::findFirst([
            'conditions' => 'sSelfPhone = :phone: AND tExpireTime >= :nowTime: AND iCodeType = :type:',
            'bind'       => ['phone' => $phone, 'nowTime' => date('Y-m-d H:i:s'), 'type' => $type],
            'order'      => 'iVCId DESC'
        ]);
        if (!$checkCode || $checkCode->iVCode != $validCode) {
            return false;
        }
        $checkCode->iState = 1;
        $checkCode->save();
        return true;
    }
}
